package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.anno.Log;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageBean;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;


    @Override
    public PageBean page(Integer page, Integer pageSize, String name, Short gender, LocalDate begin, LocalDate end) {
      /*  //数据总量
        long total = empMapper.count();

        //当前页的数据
        int startIndex = (page - 1) * pageSize;//开始索引
        List<Emp> rows = empMapper.pageQuery(startIndex,pageSize);*/

        //PageHelper实现分页查询
        PageHelper.startPage(page, pageSize);
        Page<Emp> pages = empMapper.list(name,gender,begin,end);
        return new PageBean(pages.getTotal(),pages.getResult());
    }

    @Override
    @Log
    public void deleteEmpById(List<Integer> ids) {
        //调用mapper完成删除
        empMapper.deleteById(ids);
    }

    @Override
    @Log
    public void saveEmp(Emp emp) {
        //基础字段的补充
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        //调用mapper层
        empMapper.insert(emp);
    }

    @Override
    public Emp getById(Integer id) {
        //调用mapper层获取该id的数据
        Emp emp = empMapper.getById(id);
        return emp;
    }

    @Override
    @Log
    public void update(Emp emp) {
        //补充更新时间的内容
        emp.setUpdateTime(LocalDateTime.now());
        //调用mapper层完成数据的更新
        empMapper.update(emp);
    }


    @Override
    public Emp login(Emp emp) {

        return empMapper.getByUsernameAndPassword(emp);
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    @Log
    public void deleteByDeptId(Integer deptId) {
        empMapper.deleteByDeptId(deptId);
    }
}
